<template>
  <view class="mine-container" :style="{'--primary-color': primaryColor}">
    <!-- 页面加载状态 -->
    <PageLoading :show="pageLoading" :primary-color="primaryColor" loading-text="加载中..." />
    
    <!-- 页面主要内容 -->
    <view class="page-content" v-show="shouldShowContent">
    <!--顶部个人信息栏-->
    <view class="header-section" :style="{background: `linear-gradient(135deg, ${themeColorStyles.primaryColor} 0%, ${themeColorStyles.primaryColorLight} 100%)`}">
      <view class="user-profile" @click="handleProfileClick">
        <view class="avatar-section">
          <view v-if="!avatar" class="user-avatar" :style="{border: `4rpx solid ${themeColorStyles.primaryColor}`}">
            <view class="iconfont icon-people avatar-icon" :style="{color: themeColorStyles.primaryColor}"></view>
          </view>
          <image v-if="avatar" :src="avatar" class="user-avatar" mode="aspectFill"></image>
        </view>
        <view class="user-details">
          <view v-if="!isLoggedIn" class="login-prompt">
            <text class="login-text">点击登录</text>
            <text class="login-desc">登录后享受更多服务</text>
          </view>
          <view v-if="isLoggedIn" class="user-info">
            <text class="username">{{ displayName }}</text>
            <text class="user-level">普通会员</text>
          </view>
        </view>
        <view class="profile-arrow">
          <view class="iconfont icon-right"></view>
        </view>
      </view>
    </view>

    <view class="content-section">
      <!-- 我的订单卡片 -->
      <view class="order-card" :style="{boxShadow: `0 8rpx 32rpx ${themeColorStyles.primaryColorShadow}`, border: `1rpx solid ${themeColorStyles.primaryColorBorder}`}">
        <view class="card-header">
          <text class="card-title">我的订单</text>
          <view class="view-all" @click="handleViewAllOrders" :style="{background: themeColorStyles.primaryColorBgLight}">
            <text class="view-all-text" :style="{color: themeColorStyles.primaryColor}">查看全部订单</text>
            <text class="arrow-right" :style="{color: themeColorStyles.primaryColor}">›</text>
          </view>
        </view>
        <view class="order-status-list">
          <view class="order-status-item" @click="handleOrderStatus('pending')">
            <view class="status-icon">
              <image class="icon-image" :src="waitPayIcon" mode="aspectFit"></image>
            </view>
            <text class="status-text">待付款</text>
            <view class="status-badge" v-if="orderCounts.pending > 0">{{ orderCounts.pending }}</view>
          </view>
          <view class="order-status-item" @click="handleOrderStatus('shipped')">
            <view class="status-icon">
              <image class="icon-image" :src="pendingIcon" mode="aspectFit"></image>
            </view>
            <text class="status-text">待发货</text>
            <view class="status-badge" v-if="orderCounts.shipped > 0">{{ orderCounts.shipped }}</view>
          </view>
          <view class="order-status-item" @click="handleOrderStatus('delivered')">
            <view class="status-icon">
              <image class="icon-image" :src="takeDeliveryIcon" mode="aspectFit"></image>
            </view>
            <text class="status-text">待收货</text>
            <view class="status-badge" v-if="orderCounts.delivered > 0">{{ orderCounts.delivered }}</view>
          </view>
        </view>
      </view>

      <!-- 功能菜单卡片 -->
      <view class="menu-card" :style="{boxShadow: `0 8rpx 32rpx ${themeColorStyles.primaryColorShadow}`, border: `1rpx solid ${themeColorStyles.primaryColorBorder}`}">
        <view class="menu-list">
          <!-- 我的优惠券 -->
          <view class="menu-item" @click="handleCoupon">
            <view class="menu-icon">
              <image class="icon-image" :src="couponIcon" mode="aspectFit"></image>
            </view>
            <text class="menu-text">我的优惠券</text>
            <text class="menu-arrow" :style="{color: themeColorStyles.primaryColor}">›</text>
          </view>
          <view class="menu-item" @click="handleAddressManage">
            <view class="menu-icon">
              <image class="icon-image" :src="addrIcon" mode="aspectFit"></image>
            </view>
            <text class="menu-text">地址管理</text>
            <text class="menu-arrow" :style="{color: themeColorStyles.primaryColor}">›</text>
          </view>
          <view class="menu-item" @click="handleFootprint">
            <view class="menu-icon">
              <image class="icon-image" :src="myFootIcon" mode="aspectFit"></image>
            </view>
            <text class="menu-text">我的足迹</text>
            <text class="menu-arrow" :style="{color: themeColorStyles.primaryColor}">›</text>
          </view>
          <view class="menu-item" @click="handleCustomerService">
            <view class="menu-icon">
              <image class="icon-image" :src="linkUsIcon" mode="aspectFit"></image>
            </view>
            <text class="menu-text">联系客服</text>
            <text class="menu-arrow" :style="{color: themeColorStyles.primaryColor}">›</text>
          </view>
          <view class="menu-item" @click="handleAbout">
            <view class="menu-icon">
              <image class="icon-image" :src="aboutIcon" mode="aspectFit"></image>
            </view>
            <text class="menu-text">关于我们</text>
            <text class="menu-arrow" :style="{color: themeColorStyles.primaryColor}">›</text>
          </view>
        </view>
      </view>

      <!-- 底部信息 -->
      <view class="footer-info">
        <text class="app-name">{{programConfig.aboutShopName || '迭代猫'}}</text>
        <text class="app-version">{{programConfig.remark || '电商小程序在线商城'}}</text>
      </view>
    </view>
    
    <!-- 底部安全区域，避免内容被TabBar遮挡 -->
    <view class="tabbar-safe-area"></view>
    
    <!-- 自定义TabBar -->
    <CustomTabbar :currentPath="'pages/mine/index'" />
    </view>
  </view>
</template>

<script>
  import { getOrderStats } from '@/api/order'
  import { checkLoginStatus, handleApiError } from '@/utils/loginCheck'
  import { getPublicProgramConfig } from '@/api/programConfig'
  import { getMineIconPath, getThemeColorFromGlobal, getThemePrimaryColor } from '@/utils/themeUtils'
  import PageLoading from '@/components/PageLoading/index.vue'
  import pageLoadingMixin from '@/mixins/pageLoading.js'
  import { trackEvent } from '@/utils/eventTracker.js'
  
  export default {
    components: {
      PageLoading
    },
    mixins: [pageLoadingMixin],
    data() {
      return {
        themeColor: '1', // 默认主题色
        orderCounts: {
          pending: 0,
          shipped: 0,
          delivered: 0
        },
        programConfig: {
          aboutShopName: '',
          remark: ''
        }
      }
    },
    computed: {
      avatar() {
        return this.$store.state.user.avatar
      },
      // 是否已登录（优先根据token判断，其次根据昵称/用户名）
      isLoggedIn() {
        const u = this.$store.state.user || {}
        return !!u.token || !!u.nickName || !!u.name
      },
      // 显示用户昵称，如果没有昵称则显示用户名；若尚未拉取用户信息但已登录，则显示“已登录”
      displayName() {
        const userInfo = this.$store.state.user || {}
        return userInfo.nickName || userInfo.name || (this.isLoggedIn ? '已登录' : '')
      },
      // 动态主题色
      primaryColor() {
        return getThemePrimaryColor(this.themeColor)
      },
      // 动态主题色样式（用于小程序环境）
      themeColorStyles() {
        const primaryColor = this.primaryColor
        const rgb = this.hexToRgb(primaryColor)
        if (!rgb) return {}
        
        return {
          primaryColorShadow: `rgba(${rgb.r}, ${rgb.g}, ${rgb.b}, 0.08)`,
          primaryColorShadowHover: `rgba(${rgb.r}, ${rgb.g}, ${rgb.b}, 0.15)`,
          primaryColorBorder: `rgba(${rgb.r}, ${rgb.g}, ${rgb.b}, 0.1)`,
          primaryColorBgLight: `rgba(${rgb.r}, ${rgb.g}, ${rgb.b}, 0.1)`,
          primaryColorLight: this.lightenColor(primaryColor, 20),
          primaryColor: primaryColor
        }
      },
      // 动态订单状态图标
      waitPayIcon() {
        return getMineIconPath(this.themeColor, 'wait_pay')
      },
      pendingIcon() {
        return getMineIconPath(this.themeColor, 'pending')
      },
      takeDeliveryIcon() {
        return getMineIconPath(this.themeColor, 'take_delivery')
      },
      // 动态菜单图标
      couponIcon() {
        return getMineIconPath(this.themeColor, 'coupon')
      },
      addrIcon() {
        return getMineIconPath(this.themeColor, 'addr')
      },
      myFootIcon() {
        return getMineIconPath(this.themeColor, 'my_foot')
      },
      linkUsIcon() {
        return getMineIconPath(this.themeColor, 'link_us')
      },
      aboutIcon() {
        return getMineIconPath(this.themeColor, 'about')
      }
    },
    async onLoad() {
      // 开始页面加载
      this.startPageLoading()
      
      try {
        // 初始化主题色
        await this.initThemeColor()
        this.markThemeLoaded()
        
        // 页面加载时获取订单统计数据
        await this.loadOrderStats()
        // 获取小程序配置
        await this.loadProgramConfig()
        
        // 标记数据已加载
        this.markDataLoaded()
      } catch (error) {
        console.error('用户中心页面加载失败:', error)
        this.forceCompletePageLoading()
      }
    },
    onShow() {
      // 页面显示时刷新订单统计数据
      this.loadOrderStats()
      // 刷新用户信息
      this.refreshUserInfo()
    },
    methods: {
      // 初始化主题色
      async initThemeColor() {
        const themeColor = await getThemeColorFromGlobal()
        this.themeColor = themeColor
        this.setThemeColorVariables()
      },
      
      // 设置主题色CSS变量
      setThemeColorVariables() {
        const primaryColor = getThemePrimaryColor(this.themeColor)
        // 将十六进制颜色转换为RGB值
        const rgb = this.hexToRgb(primaryColor)
        if (rgb) {
          // 在小程序环境中，使用uni.setStorageSync存储主题色变量
          // #ifdef MP
          uni.setStorageSync('themeColorVariables', {
            '--primary-color-shadow': `rgba(${rgb.r}, ${rgb.g}, ${rgb.b}, 0.08)`,
            '--primary-color-shadow-hover': `rgba(${rgb.r}, ${rgb.g}, ${rgb.b}, 0.15)`,
            '--primary-color-border': `rgba(${rgb.r}, ${rgb.g}, ${rgb.b}, 0.1)`,
            '--primary-color-bg-light': `rgba(${rgb.r}, ${rgb.g}, ${rgb.b}, 0.1)`
          })
          // #endif
          
          // 在H5环境中，设置CSS变量
          // #ifdef H5
          if (typeof document !== 'undefined' && document.documentElement) {
            const style = document.documentElement.style
            style.setProperty('--primary-color-shadow', `rgba(${rgb.r}, ${rgb.g}, ${rgb.b}, 0.08)`)
            style.setProperty('--primary-color-shadow-hover', `rgba(${rgb.r}, ${rgb.g}, ${rgb.b}, 0.15)`)
            style.setProperty('--primary-color-border', `rgba(${rgb.r}, ${rgb.g}, ${rgb.b}, 0.1)`)
            style.setProperty('--primary-color-bg-light', `rgba(${rgb.r}, ${rgb.g}, ${rgb.b}, 0.1)`)
          }
          // #endif
        }
      },
      
      // 十六进制颜色转RGB
      hexToRgb(hex) {
        const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex)
        return result ? {
          r: parseInt(result[1], 16),
          g: parseInt(result[2], 16),
          b: parseInt(result[3], 16)
        } : null
      },
      
      // 颜色变亮函数
      lightenColor(color, percent) {
        const rgb = this.hexToRgb(color)
        if (!rgb) return color
        
        const r = Math.min(255, Math.floor(rgb.r + (255 - rgb.r) * percent / 100))
        const g = Math.min(255, Math.floor(rgb.g + (255 - rgb.g) * percent / 100))
        const b = Math.min(255, Math.floor(rgb.b + (255 - rgb.b) * percent / 100))
        
        return `#${r.toString(16).padStart(2, '0')}${g.toString(16).padStart(2, '0')}${b.toString(16).padStart(2, '0')}`
      },
      // 加载订单统计数据
      async loadOrderStats() {
        try {
          // 使用统一的登录检测
          const loginResult = await checkLoginStatus({ showToast: false, autoRedirect: false })
          if (!loginResult.isLoggedIn) {
            return
          }
          
          const response = await getOrderStats(loginResult.userId)
          if (response.code === 200 && response.data) {
            this.orderCounts = {
              pending: response.data.pending || 0,
              shipped: response.data.shipped || 0,
              delivered: response.data.delivered || 0
            }
          } else {
            // console.error('获取订单统计失败:', response.msg)
          }
        } catch (error) {
          // console.error('获取订单统计异常:', error)
          // 使用统一的错误处理
          handleApiError(error, {
            showToast: true,
            autoRedirect: true,
            autoWechatLogin: true
          })
        }
      },
      // 加载小程序配置
      async loadProgramConfig() {
        try {
          // 使用 App.vue 中的实时获取配置方法
          const app = getApp()
          const config = await app.getProgramConfig()
          
          if (config) {
            this.programConfig = {
              aboutShopName: config.aboutShopName || '迭代猫',
              remark: config.remark || '电商小程序APP在线商城'
            }
          } else {
            // console.error('获取小程序配置失败')
            // 使用默认配置
            this.programConfig = {
              aboutShopName: '迭代猫',
              remark: '电商小程序APP在线商城'
            }
          }
        } catch (error) {
          // console.error('获取小程序配置异常:', error)
          // 使用默认配置
          this.programConfig = {
            aboutShopName: '迭代猫',
            remark: '电商小程序APP在线商城'
          }
        }
      },
      handleToInfo() {
        this.$tab.navigateTo('/pages/mine/info/index')
      },
      // 处理个人信息卡片点击事件
      async handleProfileClick() {
        trackEvent('mine_profile_click', { isLoggedIn: this.isLoggedIn })
        if (!this.isLoggedIn) {
          // 调用统一登录检查弹窗，用户点击“一键登录”后自动跳转到登录页
          const result = await checkLoginStatus({ showToast: true, autoRedirect: true, redirectUrl: '/pages/login' })
          if (!result.isLoggedIn) {
            // 弹窗由checkLoginStatus管理，用户选择“一键登录”后才跳转
            return
          }
        }
        // 已登录或登录完成后进入个人信息
        this.handleToInfo()
      },
      handleToEditInfo() {
        this.$tab.navigateTo('/pages/mine/info/edit')
      },
      handleToLogin() {
        this.$tab.reLaunch('/pages/login')
      },
      handleToAvatar() {
        this.$tab.navigateTo('/pages/mine/avatar/index')
      },
      handleAbout() {
        this.$tab.navigateTo('/pages/mine/about/index')
      },
      // 订单相关方法
      handleViewAllOrders() {
        this.$tab.navigateTo('/pages/order/index')
      },
      handleOrderStatus(status) {
        // 将状态映射到正确的tab索引
        const tabMap = {
          'pending': 1,    // 待付款对应tab索引1
          'shipped': 2,    // 待发货对应tab索引2
          'delivered': 3   // 待收货对应tab索引3
        }
        const tabIndex = tabMap[status]
        if (tabIndex !== undefined) {
          this.$tab.navigateTo(`/pages/order/index?tab=${tabIndex}`)
        }
      },
      getStatusText(status) {
        const statusMap = {
          pending: '待付款订单',
          shipped: '待发货订单',
          delivered: '待收货订单',
          all: '全部订单'
        }
        return statusMap[status] || '订单'
      },
      // 刷新用户信息
      refreshUserInfo() {
        try {
          // 触发store中的GetInfo action来刷新用户信息
          if (this.$store.state.user.token) {
            this.$store.dispatch('GetInfo')
          }
        } catch (error) {
          console.error('刷新用户信息失败:', error)
        }
      },
      // 功能菜单方法
      handleCoupon() {
        this.$tab.navigateTo('/pages/coupon/index')
      },
      handleAddressManage() {
        this.$tab.navigateTo('/pages/address/index')
      },
      handleFootprint() {
        this.$tab.navigateTo('/pages/footprint/index')
      },
      handleCustomerService() {
        this.$tab.navigateTo('/pages/contact/index')
      }
    }
  }
</script>

<style scoped>
/* 页面容器 */
.mine-container {
  min-height: 100vh;
  background: #F5F7FA;
  display: flex;
  flex-direction: column;
  padding-bottom: 160rpx; /* 增加底部间距避免TabBar遮挡 */
}

/* 头部区域 */
.header-section {
  padding: 40rpx 32rpx 60rpx;
  position: relative;
}

.user-profile {
  display: flex;
  align-items: center;
}

.avatar-section {
  margin-right: 24rpx;
}

.user-avatar {
  width: 100rpx;
  height: 100rpx;
  border-radius: 50rpx;
  background: #FFFFFF;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.1);
}

.avatar-icon {
  font-size: 48rpx;
}

.user-details {
  flex: 1;
}

.login-text {
  display: block;
  font-size: 32rpx;
  font-weight: 500;
  color: #FFFFFF;
  margin-bottom: 8rpx;
}

.login-desc {
  display: block;
  font-size: 26rpx;
  color: rgba(255, 255, 255, 0.8);
}

.username {
  display: block;
  font-size: 32rpx;
  font-weight: 500;
  color: #FFFFFF;
  margin-bottom: 8rpx;
}

.user-level {
  display: inline-block;
  font-size: 22rpx;
  color: #FFFFFF;
  background: rgba(255, 255, 255, 0.2);
  padding: 6rpx 12rpx;
  border-radius: 12rpx;
}

.profile-arrow .iconfont {
  font-size: 28rpx;
  color: #FFFFFF;
}

/* 内容区域 */
.content-section {
  flex: 1;
  padding: 48rpx 24rpx 32rpx;
  margin-top: -30rpx;
  position: relative;
  z-index: 1;
}

/* 我的订单卡片 */
.order-card {
  background: #FFFFFF;
  border-radius: 20rpx;
  padding: 32rpx;
  margin-top: 24rpx;
  margin-bottom: 32rpx;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 32rpx;
}

.card-title {
  font-size: 32rpx;
  font-weight: 600;
  color: #1A1A1A;
}

.view-all {
  display: flex;
  align-items: center;
  padding: 8rpx 16rpx;
  border-radius: 16rpx;
  transition: all 0.3s ease;
}

.view-all:active {
  transform: scale(0.95);
}

.view-all-text {
  font-size: 26rpx;
  margin-right: 8rpx;
  font-weight: 500;
}

.arrow-right {
  font-size: 32rpx;
  font-weight: bold;
}

.order-status-list {
  display: flex;
  justify-content: space-between;
  gap: 24rpx;
}

.order-status-item {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  position: relative;
  padding: 20rpx 12rpx;
  border-radius: 16rpx;
  transition: all 0.3s ease;
}

.order-status-item:active {
  transform: scale(0.95);
}

.status-icon {
  width: 64rpx;
  height: 64rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 16rpx;
}

.status-icon .icon-image {
  width: 48rpx;
  height: 48rpx;
}

.status-text {
  font-size: 24rpx;
  color: #333333;
  text-align: center;
  font-weight: 500;
}

.status-badge {
  position: absolute;
  top: 8rpx;
  right: 8rpx;
  background: #FF6B6B;
  color: #FFFFFF;
  font-size: 20rpx;
  font-weight: 600;
  padding: 4rpx 8rpx;
  border-radius: 12rpx;
  min-width: 24rpx;
  text-align: center;
  line-height: 1;
  box-shadow: 0 2rpx 8rpx rgba(255, 107, 107, 0.3);
}

/* 功能菜单卡片 */
.menu-card {
  background: #FFFFFF;
  border-radius: 20rpx;
  margin-bottom: 32rpx;
  overflow: hidden;
}

.menu-list {
  padding: 0;
}

.menu-item {
  display: flex;
  align-items: center;
  padding: 28rpx 32rpx;
  border-bottom: 1rpx solid #F5F5F5;
  transition: all 0.3s ease;
  position: relative;
}

.menu-item:last-child {
  border-bottom: none;
}

.menu-item::after {
  content: '';
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  width: 6rpx;
  height: 0;
  background: linear-gradient(135deg, var(--primary-color, #6B9FFF) 0%, color-mix(in srgb, var(--primary-color, #6B9FFF) 90%, #000000) 100%);
  border-radius: 0 3rpx 3rpx 0;
  transition: height 0.3s ease;
}

.menu-item:active::after {
  height: 60%;
}

.menu-icon {
  width: 64rpx;
  height: 64rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 24rpx;
  transition: all 0.3s ease;
}

.menu-item:active .menu-icon {
  transform: scale(0.9);
}

.menu-icon .icon-image {
  width: 48rpx;
  height: 48rpx;
  transition: all 0.3s ease;
}

.menu-item:active .menu-icon .icon-image {
  transform: scale(0.95);
}

.menu-text {
  flex: 1;
  font-size: 30rpx;
  color: #1A1A1A;
  font-weight: 500;
}

.menu-arrow {
  font-size: 32rpx;
  color: #CCCCCC;
  font-weight: bold;
  transition: all 0.3s ease;
}

/* 底部信息 */
.footer-info {
  text-align: center;
  padding: 48rpx 32rpx 64rpx;
  margin: 0 24rpx;
}

.app-name {
  display: block;
  font-size: 28rpx;
  font-weight: 500;
  color: #999999;
  margin-bottom: 12rpx;
  letter-spacing: 1rpx;
}

.app-version {
  display: block;
  font-size: 24rpx;
  color: #CCCCCC;
  opacity: 0.8;
  line-height: 1.5;
}

/* 动画效果 */
@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(20rpx);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.quick-orders,
.function-menu {
  animation: fadeIn 0.4s ease-out;
}

.quick-orders {
  animation-delay: 0.1s;
}

.function-menu {
  animation-delay: 0.2s;
}

/* TabBar安全区域 */
.tabbar-safe-area {
  height: 200rpx;
  padding-bottom: constant(safe-area-inset-bottom);
  padding-bottom: env(safe-area-inset-bottom);
}
</style>
